package com.luoxiang.socialandroid.activity

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.constraintlayout.motion.widget.MotionLayout
import androidx.constraintlayout.motion.widget.MotionLayout.TransitionListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.gson.Gson
import com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID
import com.luoxiang.lib_common.common.Constants.MmkvConst.DOMAIN
import com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA
import com.luoxiang.lib_common.common.Constants.MmkvConst.KEY
import com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN
import com.luoxiang.lib_common.utils.MmkvUtil
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.base.BaseActivity
import com.luoxiang.socialandroid.bean.NumberBean
import com.luoxiang.socialandroid.bean.OurinfoBean
import com.luoxiang.socialandroid.databinding.ActivityOnlineMatchingSuccessBinding
import com.luoxiang.socialandroid.dialog.TipDialog
import com.luoxiang.socialandroid.utils.AESUtil
import com.luoxiang.socialandroid.utils.CustomClickListener
import com.luoxiang.socialandroid.utils.MmkvUtil.decodeInt
import com.luoxiang.socialandroid.utils.NetUtils
import com.lxj.xpopup.XPopup
import com.netease.yunxin.nertc.ui.CallKitUI.startSingleCall
import com.netease.yunxin.nertc.ui.base.CallParam
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*

class OnlineMatchingSuccessActivity : BaseActivity() {
    private lateinit var mViewBinding: ActivityOnlineMatchingSuccessBinding
    private var userIdcall = -1
    private var userIdcallname: String? = null
    private var userIdcallLocation: String? = null
    private var userIdcallicon: String? = null
    override fun initLayout(savedInstanceState: Bundle?) {
        mViewBinding = ActivityOnlineMatchingSuccessBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
        setStatusBarTranslucent()
        Glide.with(this)
            .load(R.drawable.icon_online_matching_bg)
            .into(mViewBinding.tvSuccessMatching)
    }

    override fun initView() {
        lifecycleScope.launch {
            var index = 0
            while (true) {
                delay(1000)
                mViewBinding.textTitle.text = when (index) {
                    0 -> {
                        index = 1
                        getString(R.string.mi_pipeichenggong_1)
                    }
                    1 -> {
                        index = 2
                        getString(R.string.mi_pipeichenggong_2)
                    }
                    2 -> {
                        index = 0
                        getString(R.string.mi_pipeichenggong_3)
                    }
                    else -> {
                        index = 0
                        getString(R.string.mi_pipeichenggong_3)
                    }
                }
            }
        }
        mViewBinding.motionLayout.post {
            mViewBinding.motionLayout.transitionToEnd()
        }
        userIdcallname = intent.getStringExtra("userIdcallname")//对方UserId
        userIdcallLocation = intent.getStringExtra("userIdcallprovince")//对方UserId
        userIdcallicon = intent.getStringExtra("userIdcallicon")//对方头像
        mViewBinding.textView21.text = userIdcallname
        mViewBinding.tvLocation.text = userIdcallLocation
        Glide.with(this)
            .load(DOMAIN + userIdcallicon)
            .transform(RoundedCorners(32))
            .into(mViewBinding.imageView14)
        Glide.with(this)
            .load(DOMAIN + MmkvUtil.decodeString("usericon"))
            .transform(RoundedCorners(32))
            .into(mViewBinding.imageView13)
        mViewBinding.imageView7.setOnClickListener(object : CustomClickListener() {
            override fun onSingleClick() {
                finish()
            }

            override fun onFastClick() {
            }

        })
    }

    private fun getimPre(extra: String, toUserId: String, token: String) {
        NetUtils.getInstance().apiService.getimPre(extra, toUserId, token)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean?> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(value: NumberBean?) {
                    val data = value?.data
                    var decryptStr: String? = null
                    try {
                        decryptStr = AESUtil.aesDecryptString(data, KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    LogUtils.i("decryptStr10", decryptStr)
                    val gson = Gson()
                    val bean = gson.fromJson(decryptStr, OurinfoBean::class.java)
                    TestActivity.ourinfoBean = bean
                    when (bean.code) {
                        0 -> {
                            //可以发起通话
                            lifecycleScope.launch {
                                delay(2000)
                                if(lifecycle.currentState != Lifecycle.State.RESUMED){
                                    Toast.makeText(
                                        this@OnlineMatchingSuccessActivity,
                                        "匹配失败：当前通话异常或正在通话中",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    finish()
                                    return@launch
                                }
                                val accId = decodeInt(ACCID)!!
                                val id = UUID.randomUUID().toString().replace("-", "")
                                val param = CallParam.createSingleCallParam(
                                    2,
                                    accId.toString() + "",
                                    toUserId + "",
                                    null,
                                    null,
                                    id
                                )
                                startSingleCall(this@OnlineMatchingSuccessActivity, param)
                                finish()
                            }
                        }
                        106 -> {
                            ToastUtils.showShort(bean.msg)
                            val tipDialog = TipDialog(this@OnlineMatchingSuccessActivity)
                            tipDialog.setTitle(getString(R.string.mi_caozuotishi))
                            tipDialog.setCancel(getString(R.string.mi_quxiao))
                            tipDialog.setContent(getString(R.string.mi_dialog_yuebuzu_tip))
                            tipDialog.setConfirm(getString(R.string.mi_chongzhi))
                            tipDialog.setOnCancelClickListener {
                                tipDialog.dismiss()
                                val intent = Intent(
                                    this@OnlineMatchingSuccessActivity,
                                    OnlineMatchingFailureActivity::class.java
                                )
                                startActivity(intent)
                                finish()
                                null
                            }
                            tipDialog.setOnConfirmClickListener {
                                val intent = Intent(
                                    this@OnlineMatchingSuccessActivity,
                                    WalletActivity::class.java
                                )
                                startActivity(intent)
                                finish()
                                tipDialog.dismiss()
                                null
                            }
                            XPopup.Builder(this@OnlineMatchingSuccessActivity)
                                .asCustom(tipDialog)
                                .show()
                        }
                        else -> {
                            ToastUtils.showShort(bean.msg)
                            val intent = Intent(
                                this@OnlineMatchingSuccessActivity,
                                OnlineMatchingFailureActivity::class.java
                            )
                            startActivity(intent)
                            finish()
                        }
                    }
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}

            })
    }

    override fun initListener() {
        mViewBinding.motionLayout.setTransitionListener(object : TransitionListener {
            override fun onTransitionStarted(
                motionLayout: MotionLayout?,
                startId: Int,
                endId: Int
            ) {
            }

            override fun onTransitionChange(
                motionLayout: MotionLayout?,
                startId: Int,
                endId: Int,
                progress: Float
            ) {
            }

            override fun onTransitionCompleted(motionLayout: MotionLayout?, currentId: Int) {
                //todo 这里预检接口
                userIdcall = intent.getIntExtra("userIdcall", -1)//对方UserId
                MmkvUtil.decodeString(TOKEN)?.let { getimPre(EXTRA, userIdcall.toString(), it) }

            }

            override fun onTransitionTrigger(
                motionLayout: MotionLayout?,
                triggerId: Int,
                positive: Boolean,
                progress: Float
            ) {
            }
        })
    }
}